package com.twelve.all.utils;

import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.twelve.all.R;

/**
 * author: 张龙臣
 * date: 2019-05-05.
 */

public class EditTextHelper {

    /**
     * 初始化密码输入框，使其有密码显示和隐藏的功能
     *
     * @param editText  密码输入框
     * @param imageView 被点击切换显示和隐藏的图片
     */
    public static void passwordType(final EditText editText, final ImageView imageView) {
        //默认将密码设置成不可见（inputType设置在代码中是无效的）
        editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        imageView.setImageResource(R.drawable.able_see_password);
        imageView.setTag(false);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = imageView.getTag();
                //当前密码是否可见
                boolean ableSee = false;
                if (tag != null) {
                    ableSee = (boolean) tag;
                }
                if (ableSee) {
                    imageView.setTag(false);
                    editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    imageView.setImageResource(R.drawable.able_see_password);
                } else {
                    imageView.setTag(true);
                    //将密码设置成可见
                    editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    imageView.setImageResource(R.drawable.enable_see_password);
                }
                //将光标移动到输入框末尾
                editText.setSelection(editText.getText().toString().length());
            }
        });
    }

}
